/***************
 * Upload Importer Window
 *
 * Button to start importing a CSV into the tank, and feedback fields
 */
AIR2.Upload.Importer = function() {
    var panel;

    // organization chooser, restricted to WRITER role
    var orgfield = new AIR2.UI.SearchBox({
        fieldLabel: 'Organization',
        searchUrl: AIR2.HOMEURL + '/organization',
        valueField: 'org_uuid',
        displayField: 'org_display_name',
        hideTrigger: false,
        allowBlank: false,
        disabled: true,
        baseParams: {sort: 'org_display_name'},
        formatComboListItem: function(values) {
            return values.org_display_name;
        }
    });
    if (AIR2.USERINFO.type != "S") {
        orgfield.store.on('load', function(store) {
            store.each(function(rec) {
                if (!(AIR2.AUTHZ.WRITER & AIR2.USERAUTHZ[rec.data.org_uuid])) {
                    store.remove(rec);
                }
            });
        });
    }

    // project chooser
    var prjfield = new AIR2.UI.SearchBox({
        fieldLabel: 'Project',
        searchUrl: AIR2.HOMEURL + '/project',
        valueField: 'prj_uuid',
        displayField: 'prj_display_name',
        hideTrigger: false,
        allowBlank: false,
        disabled: true,
        formatComboListItem: function(v) {
            return v.prj_display_name;
        }
    });
    orgfield.on('valid', function() {
        if (!orgfield.disabled) prjfield.enable();
    });
    orgfield.on('invalid', function() {
        prjfield.disable();
    });
    orgfield.on('select', function() {
        if (orgfield.getValue() != orgfield.startValue) {
            prjfield.clearValue();

            // reload from new URL
            var org = AIR2.HOMEURL+'/organization/'+orgfield.getValue()+'/projects.json';
            prjfield.store.proxy.setApi(Ext.data.Api.actions.read, org);
            prjfield.store.reload();
        }
    });

    // activity choosers
    var actmfield = new AIR2.UI.SearchBox({
        fieldLabel: 'Activity',
        searchUrl: AIR2.HOMEURL+'/upload/activity',
        valueField: 'actm_id',
        displayField: 'actm_name',
        hideTrigger: false,
        allowBlank: false,
        disabled: true,
        formatComboListItem: function(v) {
            return v.actm_name;
        }
    });
    var dtimfield = new Ext.form.DateField({
        fieldLabel: 'Activity Date',
        allowBlank: false,
        disabled: true
    });
    var notesfield = new Ext.form.TextArea({
        hideLabel: true,
        width: 280,
        allowBlank: false,
        disabled: true,
        emptyText: 'Description of upload activity',
        msgTarget: 'under'
    });

    // status message
    var msg = new Ext.form.DisplayField({
        cls: 'upload-import-msg',
        hideLabel: true,
        msgTarget: 'under'
    });
    var btn = new AIR2.UI.Button({
        air2type: 'BLUE',
        air2size: 'MEDIUM',
        text: 'Import to Tank',
        disabled: true,
        handler: function() {
            if (!btn.tankUUID) return;
            if (!panel.getForm().isValid()) return;

            // remote waiting message
            btn.remoteWait.alignTo(btn.btnEl, 'l-r', [5,0]);
            btn.remoteWait.show();
            btn.disable();
            Ext.Ajax.request({
                url: AIR2.HOMEURL+'/upload/'+btn.tankUUID+'/submit.json',
                params: {
                    org_uuid: orgfield.getValue(),
                    prj_uuid: prjfield.getValue(),
                    tank_actm_id: actmfield.getValue(),
                    tank_notes: notesfield.getValue(),
                    tank_dtim: dtimfield.getValue()
                },
                callback: function(opts, success, resp) {
                    btn.remoteWait.hide();
                    if (success) {
                        var data = Ext.util.JSON.decode(resp.responseText);
                        if (data.radix) {
                            panel.fireEvent('aftersubmit', data.success, data);
                        }
                        else {
                            btn.enable();
                            msg.markInvalid(data.message);
                        }
                    }
                    else {
                        msg.markInvalid('Encountered a server error');
                    }
                }
            });
        },
        listeners: {
            render: function() {
                btn.remoteWait = btn.el.createChild({cls: 'air2-form-remote-wait'});
            }
        }
    });

    panel = new Ext.form.FormPanel({
        cls: 'air2-upload-import',
        unstyled: true,
        padding: '2px 20px',
        items: {
            xtype: 'fieldset',
            title: 'Submit Activity',
            items: [{
                xtype: 'container',
                layout: 'column',
                items: [{
                    xtype: 'container',
                    columnWidth: .5,
                    layout: 'form',
                    labelWidth: 75,
                    items: [orgfield, prjfield, actmfield, dtimfield]
                },{
                    xtype: 'container',
                    columnWidth: .5,
                    layout: 'form',
                    labelWidth: 75,
                    items: [notesfield]
                }]
            },{
                xtype: 'container',
                layout: 'column',
                items: [{
                    xtype: 'container',
                    columnWidth: .2,
                    items: btn
                },{
                    xtype: 'container',
                    columnWidth: .8,
                    layout: 'form',
                    items: msg
                }]
            }]
        },
        setFormDisabled: function(disabled) {
            orgfield.setDisabled(disabled);
            prjfield.setDisabled(disabled);
            actmfield.setDisabled(disabled);
            notesfield.setDisabled(disabled);
            dtimfield.setDisabled(disabled);
            btn.setDisabled(disabled);
        },
        setTankData: function(data) {
            btn.tankUUID = false;
            msg.clearInvalid();

            var meta = (data) ? Ext.decode(data.tank_meta) : {};
            if (meta.submit_success) {
                //done ... disable everything (including button)
                this.setFormDisabled(true);
                msg.setValue(meta.submit_message);
            }
            else if (meta.valid_header) {
                //header is valid... enable everything
                this.setFormDisabled(false);
                btn.tankUUID = data.tank_uuid;
                if (meta.submit_message) msg.markInvalid(meta.submit_message);
            }
            else {
                //mask everything
                this.setFormDisabled(true);
            }

            orgfield.selectRawValue(data.org_uuid);
            prjfield.selectRawValue(data.prj_uuid);
            actmfield.selectRawValue(data.tank_actm_id);
            notesfield.setValue(data.tank_notes);

            // make sure our dtim is parsed
            var dt = Date.parseDate(data.tank_dtim, "Y-m-d H:i:s");
            dtimfield.setValue(dt ? dt : data.tank_dtim);
        }
    });

    return panel;
}